package handling.login;

import client.MapleClient;
import client.MapleEnumClass.AuthReply;
import com.alibaba.druid.pool.DruidPooledConnection;
import configs.ServerConfig;
import database.DatabaseConnection;
import handling.channel.ChannelServer;
import handling.login.handler.ServerlistRequestHandler;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import server.Timer.PingTimer;
import tools.MaplePacketCreator;
import tools.packet.LoginPacket;

public class LoginWorker {
    private static final Logger log = LogManager.getLogger(LoginWorker.class.getName());
    private static long lastUpdate = 0L;

    public static void registerClient(MapleClient c, boolean useKey) {
        if (ServerConfig.WORLD_ONLYADMIN && !c.isGm() && !c.isLocalhost()) {
            c.announce(MaplePacketCreator.serverNotice(1, "当前服务器设置只能管理员进入游戏.\r\n我们目前在修复几个问题.\r\n请稍后再试."));
            c.announce(LoginPacket.getLoginFailed(AuthReply.GAME_DEFINITION_INFO));
        } else {
            if (System.currentTimeMillis() - lastUpdate > 600000L) {
                lastUpdate = System.currentTimeMillis();
                Map load = ChannelServer.getChannelLoad();
                int usersOn = 0;
                if (load == null || load.size() <= 0) {
                    lastUpdate = 0L;
                    c.announce(LoginPacket.getLoginFailed(AuthReply.GAME_CONNECTING_ACCOUNT));
                    return;
                }

                double loadFactor = (double)ServerConfig.LOGIN_USERLIMIT / ((double)LoginServer.getUserLimit() / (double)load.size() / 100.0D);
                Iterator var6 = load.entrySet().iterator();

                while(var6.hasNext()) {
                    Entry entry = (Entry)var6.next();
                    usersOn += (Integer)entry.getValue();
                    load.put(entry.getKey(), Math.min(ServerConfig.LOGIN_USERLIMIT, (int)((double)(Integer)entry.getValue() * loadFactor)));
                }

                LoginServer.setLoad(load, usersOn);
                lastUpdate = System.currentTimeMillis();
            }

            if (c.finishLogin() == 0) {
                if (!useKey) {
                    String[] channels = new String[0];
                    if (!ServerConfig.CHANNEL_VIP.isEmpty()) {
                        channels = ServerConfig.CHANNEL_VIP.split(",");
                    }

                    if (channels.length > 0) {
                        c.announce(LoginPacket.setVipChannel(channels));
                    }

                    c.announce(LoginPacket.getAuthSuccessRequest(c));
                    ServerlistRequestHandler.handlePacket(c, false);
                } else {
                    c.announce(LoginPacket.getAuthSuccessRequestX(c, false));
                }

                c.setIdleTask(PingTimer.getInstance().schedule(c.getSession()::close, 6000000L));

                try {
                    DruidPooledConnection con = DatabaseConnection.getInstance().getConnection();
                    Throwable var38 = null;

                    try {
                        PreparedStatement ps = con.prepareStatement("INSERT INTO accounts_log (accid, accname, ip, macs) VALUES (?, ?, ?, ?)");
                        Throwable var5 = null;

                        try {
                            ps.setInt(1, c.getAccID());
                            ps.setString(2, c.getAccountName());
                            ps.setString(3, c.getSessionIPAddress());
                            ps.setString(4, c.getMac());
                            ps.executeUpdate();
                        } catch (Throwable var31) {
                            var5 = var31;
                            throw var31;
                        } finally {
                            if (ps != null) {
                                if (var5 != null) {
                                    try {
                                        ps.close();
                                    } catch (Throwable var30) {
                                        var5.addSuppressed(var30);
                                    }
                                } else {
                                    ps.close();
                                }
                            }

                        }
                    } catch (Throwable var33) {
                        var38 = var33;
                        throw var33;
                    } finally {
                        if (con != null) {
                            if (var38 != null) {
                                try {
                                    con.close();
                                } catch (Throwable var29) {
                                    var38.addSuppressed(var29);
                                }
                            } else {
                                con.close();
                            }
                        }

                    }
                } catch (SQLException var35) {
                    log.error(var35);
                }

            } else {
                c.announce(LoginPacket.getLoginFailed(AuthReply.GAME_CONNECTING_ACCOUNT));
            }
        }
    }
}
